<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>图片管理</title>
<?= HTML::style('static/bootstrap-3.3.7/css/bootstrap.min.css')?>

<?= HTML::script('static/js/jquery-1.12.4.min.js')?>
<?= HTML::script('static/bootstrap-3.3.7/js/bootstrap.min.js')?>

<?= HTML::style('static/pikaday/css/pikaday.css')?>
<?= HTML::script('static/pikaday/js/pikaday.js')?>
<style>
.up-files .img-thumbnail{cursor:pointer}
.up-files .img-thumbnail:hover{border:1px solid orange}
.up-files .img-thumbnail.selected{border:1px solid blue}
abbr[data-original-title],abbr[title] {
    cursor: default;
    border-bottom: 0px dotted #777
}
.img-thumbnail{transition:none}
.btn-default:hover {
    background-color: #f6f8fa;
    border-color: 1px solid #e1e4e8;
}
</style>
</head>
<body style="padding:10px 20px">
<div class="container">
	<div class="row">
	    <div style="margin-bottom:10px">
            <button id="pickfiles" class="btn btn-default">选择文件</button>
            <button id="uploadBtn" class="btn btn-info">上传</button>
            
            <div class="pull-right col-xs-6 col-sm-6 col-md-6" style="display: none">
                <form id="search_form" class="form-inline" method="get">
                    <div class="input-group">
                        <input type="text" class="form-control" id="q" name="q" placeholder="">
                        <span class="input-group-btn">
                            <button class="btn btn-info" type="submit" id="search">查找</button>
                        </span>
                     </div>
                 </form>
             </div>
        </div>
            
        <div id="fsUploadProgress">
            <?php include __DIR__ . '/grid_incr.php';?>
        </div>
        
        <div style="clear:both"></div>
        
        <nav class="pager">
        <?php if ($pager->next_page): ?>
        <a class="btn btn-default btn-block" href="<?= $pager->url($pager->next_page) ?>"><?= '查看更多' ?></a>
        <?php endif ?>
        </nav>
            
	</div>
</div>

<style>
.up-item, .up-files{float:left;width:120px;height:90px;margin-right:6px;margin-bottom:6px;position:relative}
.up-item .close, .up-files .close{position:absolute;right:3px;top:0;}
.up-item .img-thumbnail, .up-files .img-thumbnail{width:120px;height:90px;}
.up-item .progress{position:absolute;left:0;bottom:0;width:100%;height:8px;margin:0;display:none}
</style>
<?php include __DIR__ . '/../plupload.php';?>

<script>
accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000; 

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        serverUrl = '<?= URL::site('aliyunoss/uptoken?type=article')?>'
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
        if(tt[i].checked)
        {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}

function get_signature()
{
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    /*if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {*/
        suffix = get_suffix(filename)
        g_object_name = key + random_string(10) + suffix
    //}
    return ''
}

function get_uploaded_object_name(filename)
{
    /*if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {*/
        return g_object_name
    //}
}

function set_upload_param(up, filename, ret)
{
    if (ret == false)
    {
        ret = get_signature()
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    //up.start();
}

$(function() {
	var uploader = new plupload.Uploader({
		browse_button : 'pickfiles',
		multi_selection: false,
		url : 'http://oss.aliyuncs.com',
		flash_swf_url : '<?= URL::site('static/plupload/Moxie.swf')?>',
		silverlight_xap_url : '<?= URL::site('static/plupload/Moxie.xap')?>',
		filters: {
			mime_types: [{
				title : "图片文件", 
				extensions: "jpg,gif,png"
			}],
            max_file_size : '1000kb',
			prevent_duplicates : true
	    }
	});
	uploader.init();

	uploader.bind('FilesAdded',function(up,files){
		console.log(up, files);
        plupload.each(files, function(file) {
        	var progress = new FileProgress(file, 'fsUploadProgress');
        	//$('#pickfiles').hide();
        	//$('input[type=file]').parent('div').hide();

    		var remove_btn = $('#'+file.id).find('.close');
    		remove_btn.click(function(){
    			uploader.removeFile(file);
    			$('#pickfiles').show();
            	$('input[type=file]').parent('div').show();
    		});
        });
        set_upload_param(uploader, '', false);
        //this.start();
	});
	uploader.bind('BeforeUpload',function(up, file){
		$('#'+file.id).find('.progress').show();
		
		set_upload_param(up, file.name, true);
        this.start();
	});
	uploader.bind('UploadProgress',function(up, file){
        var progress = new FileProgress(file, 'fsUploadProgress');
	    progress.setProgress(file.percent);
	});
	uploader.bind('FileUploaded',function(up, file, info){
        var progress = new FileProgress(file, 'fsUploadProgress');
        progress.setComplete(up, file, info);

        if (info.status == 200) {
        	var url = 'http://jtkj.oss-cn-beijing.aliyuncs.com/' + get_uploaded_object_name();
        //}

    	//var res = info.response;
    	//res = eval('('+res+')');
    	//if (res.status=='ok') {
    	//    var url = '/imagefly/w200/'+res.data;
    	    //$('#'+file.id).find('img').attr('src', url + '?x-oss-process=image/resize,m_fill,h_120,w_160');
    	    $('#'+file.id).find('input').val(url);
    	    $('#'+file.id).attr('class', 'up-files').find('img')
    	    .attr('src', url + '?x-oss-process=image/resize,m_fill,h_120,w_160')
    	    .attr('o-src', url);

    	    var image = new Image();
            image.src = url;
            image.onload = function() {
                var w = image.width;
                var h = image.height;
    
                $.get('/upload/add',{'img_url':url, 'file_size': file.size, 'img_width': w, 'img_height': h},function(){});
            }
        
    	}
	});

	$(document).on('click', '.up-item .close', function(){
		$(this).parents('.up-item').remove();
		$('#pickfiles').show();
    	$('input[type=file]').parent('div').show();
	});

    $('#uploadBtn').click(function() {
    	uploader.start();
    	return false;
    });
});
</script>


<script>
$(function() {
    $(document).on('click', ".up-files .img-thumbnail", function(){
        var t = $(this);
    	var selected = t.hasClass("selected");
    	selected ? t.removeClass("selected") : t.addClass("selected");
    });

	$(document).on('click', '.pager>a', function(){
		var t = $(this);
		var url = t.attr('href');
		if (url.split('#')[0].length) {
    		$.get(url, function(res) {
    			$('#fsUploadProgress').append(res.content);
    			$('.pager>a').attr('href', res.nexturl);
    			if (!res.nexturl) {
    				$('.pager').hide();
    			} 
    		});
		}
		return false;
	});

	$('#search_form').submit(function() {
		var url = $(this).attr('action');
		var params = {};
		params.q = $('input[name=q]').val();
		$.get(url, params, function(res) {
			$('#fsUploadProgress').html(res.content);
			$('.pager>a').attr('href', res.nexturl);
			if (!res.nexturl) {
				$('.pager').hide();
			} else {
				$('.pager').show();
			}
		});
		return false;
	});
	
    var picker = new Pikaday({
        field: document.getElementById('q'),
        //format: 'YYYY/MM/DD',
        minDate: new Date('2015-06-01'),
        maxDate: new Date('2018-01-12'),
        onSelect: 	function() {
            var d = this.toString();
			d = d.replace(/-/g, '/');
			$('input[name=q]').val(d);
		}
    });
});
</script>
